<?php

if (!defined('BASEPATH'))
    exit('No direct script access allowed');

class Attitude_User_Details_Controller extends CI_Controller {

    function __construct() {
        parent::__construct();
        $this->load->helper('xlsimport/php-excel-reader/excel_reader2');
        $this->load->helper('xlsimport/spreadsheetreader.php');
        $this->load->model('attitudeuserdetail', '', true);
        $this->load->model('user', '', true);
        

        if (!$this->session->userdata('logged_in')) {
            redirect('login');
        }

        $this->LoggedUser = $this->user->getLoggedUser();

        $this->load->library('authentication');$this->load->helper('t');
        $this->loggedUser = $this->authentication->getLoggedUser();$this->authentication->redirectIfNotBe(array('SS', 'KAS'));

    }

    function index($limit = '0') {

        $this->load->helper('form');

        $viewData['attitudeResults'] = $this->attitudeuserdetail->get_list($limit);

        $this->load->view(get_folder($this->loggedUser->title).'/attitude_user_details_list', $viewData);
    }

    function add($user_id) {

        $this->load->model('attitudecriteria');
        $this->load->model('attitudedetailresult');
        $this->load->model('evaluation');
        $this->load->model('Settings');
        $settings = $this->Settings->get(1);
        
        $beRatedUser = $this->user->get_user($user_id);
        if(strtotime($beRatedUser['starting_day']) >= strtotime(date('Y-5-1')))
        {
            show_404();
            exit;
        }

        $attitudeCriterias = $this->attitudecriteria->get_list('0');
        $viewData['attitudeCriterias'] = $attitudeCriterias;

        $evaluation = $this->evaluation->get_last();

        if ($this->input->post('Command') && $this->input->post('Command') == 'Add') {
            // Thực hiện form validation
            $this->load->helper(array('form', 'url'));
            $this->load->library('form_validation');
            foreach ($attitudeCriterias as $eachAC) {
                $this->form_validation->set_rules('attCriteria-' . $eachAC->id, '', 'required');
            }
            
            if ($this->form_validation->run() == FALSE) {
                $viewData['error'] = true;
                $viewData['message'] = 'Có tiêu chí chưa được đánh giá';
            } else {

                // Tạo att_detail_result
                $newADR = array(
                    'user_id' => $user_id,
                    'eid' => $evaluation['id']
                );
                $this->attitudedetailresult->insert($newADR);
                //

                $newAdrId = $this->db->insert_id();

                $totalScore = 0;
                foreach ($attitudeCriterias as $eachAC) {
                    $newRow = array(
                        'user_id' => $user_id,
                        'adr_id' => $newAdrId,
                        'ac_id' => $eachAC->id,
                        'score' => $this->input->post('attCriteria-' . $eachAC->id),
                        'comment' => $this->input->post('cmt-' . $eachAC->id)
                    );
                    $totalScore += $this->input->post('attCriteria-' . $eachAC->id);

                    $viewData['addResult'] = $this->attitudeuserdetail->insert($newRow);
                }

                // cập nhật adr
                $rating = '';
                $art_id = 0;
                if ($totalScore >= $settings['att_high_score']) {
                    $art_id = 3;
                    $rating = 'Thể hiện vượt trội';
                } else if ($totalScore >= $settings['att_medium_score']) {
                    $art_id = 2;
                    $rating = 'Có thể hiện';
                } else {
                    $art_id = 1;
                    $rating = 'Cần cải thiện';
                }

                $updateAdr = array(
                    'id' => $newAdrId,
                    'score' => $totalScore,
                    'rated_day' => date('Y-m-d H:i:s'),
                    'rating' => $rating,
                    'art_id' => $art_id
                );

                $this->attitudedetailresult->update($updateAdr);
                redirect('ss_kas/attitude_detail_results');
                return;
            }
        }
        
        $viewData['beRatedUser'] = $beRatedUser;
        $viewData['beRatedUser']['teamleaderInfo'] = $this->user->get_user_by_code($beRatedUser['teamleader_code']);
        $viewData['beRatedUser']['supervisorInfo'] = $this->user->get_user_by_code($beRatedUser['supervisor_code']);
        $viewData['beRatedUser']['rsmInfo'] = $this->user->get_user_by_code($beRatedUser['rsm_code']);


        //$adr_info = $this->attitudedetailresult->get($ar_id);
        $viewData['evaluation'] = $evaluation;
        $viewData['adr_id'] = $newAdrId;


        $this->load->view(get_folder($this->loggedUser->title).'/attitude_user_details_add', $viewData);
    }

    function edit($user_id) {
        $this->load->model('attitudecriteria');
        $this->load->model('attitudedetailresult');
        $this->load->model('evaluation');
        $this->load->model('Settings');
        $settings = $this->Settings->get(1);
        
        $beRatedUser = $this->user->get_user($user_id);
        if(strtotime($beRatedUser['starting_day']) >= strtotime(date('Y-5-1')))
        {
            show_404();
            exit;
        }
        
        $evaluation = $this->evaluation->get_last();
        $adr = $this->attitudedetailresult->get_wheres(array('user_id' => $user_id, 'eid' => $evaluation['id']));
        if($adr['status'] == 'confirmed') // trạng thái ko dc điều chỉnh: confirmed
        {
            show_404(); // cố tình gõ url thì 404 cho lẹ
            //redirect(get_folder($this->loggedUser->title).'/attitude_detail_results');
        }
        
        $attitudeCriterias = $this->attitudecriteria->get_list('0');
        $viewData['attitudeCriterias'] = $attitudeCriterias;
        
        $attUserDetails = $this->attitudeuserdetail->get_wheres(array('user_id' => $user_id, 'adr_id' => $adr['id']));
        $viewData['attUserDetails'] = $attUserDetails;

        if ($this->input->post('Command') && $this->input->post('Command') == 'Edit') {
            // Thực hiện form validation

            $this->load->helper(array('form', 'url'));
            $this->load->library('form_validation');
            foreach ($attitudeCriterias as $eachAC) {
                $this->form_validation->set_rules('attCriteria-' . $eachAC->id, '', 'required');
            }
            if ($this->form_validation->run() == FALSE) {
                $viewData['error'] = true;
                $viewData['message'] = 'Có tiêu chí chưa được đánh giá';
            } else {

                $totalScore = 0;
                foreach ($attUserDetails as $eachUD) {
                    $updateRow = array(
                        'id' => $eachUD['id'],
                        'user_id' => $user_id,
                        'adr_id' => $adr['id'],
                        'ac_id' => $eachUD['ac_id'],
                        'score' => $this->input->post('attCriteria-' . $eachUD['ac_id']),
                        'comment' => $this->input->post('cmt-' . $eachUD['ac_id'])
                    );
                    $totalScore += $this->input->post('attCriteria-' . $eachUD['ac_id']);

                    $viewData['addResult'] = $this->attitudeuserdetail->update($updateRow);
                }

                // cập nhật adr
                $rating = '';
                $art_id = 0;
                if ($totalScore >= $settings['att_high_score']) {
                    $art_id = 3;
                    $rating = 'Thể hiện vượt trội';
                } else if ($totalScore >= $settings['att_medium_score']) {
                    $art_id = 2;
                    $rating = 'Có thể hiện';
                } else {
                    $art_id = 1;
                    $rating = 'Cần cải thiện';
                }

                $updateAdr = array(
                    'id' => $adr['id'],
                    'score' => $totalScore,
                    'rated_day' => date('Y-m-d H:i:s'),
                    'rating' => $rating,
                    'art_id' => $art_id,
                    'status' => $adr['status'] == 'rejected' ? 'review' : 'waiting'
                );

                $this->attitudedetailresult->update($updateAdr);
            }
        }

        $viewData['beRatedUser'] = $beRatedUser;
        $viewData['beRatedUser']['teamleaderInfo'] = $this->user->get_user_by_code($beRatedUser['teamleader_code']);
        $viewData['beRatedUser']['supervisorInfo'] = $this->user->get_user_by_code($beRatedUser['supervisor_code']);
        $viewData['beRatedUser']['rsmInfo'] = $this->user->get_user_by_code($beRatedUser['rsm_code']);

        $attUserDetails = $this->attitudeuserdetail->get_wheres(array('user_id' => $user_id, 'adr_id' => $adr['id']));
        $viewData['attUserDetails'] = $attUserDetails;


        foreach ($viewData['attitudeCriterias'] as &$each) {

            foreach ($attUserDetails as $eachUD) {
                if ($each->id == $eachUD['ac_id']) {
                    $each->checked = $eachUD['score'];
                    $each->comment = $eachUD['comment'];
                }
            }
        }


        //$adr_info = $this->attitudedetailresult->get($ar_id);
        $viewData['evaluation'] = $evaluation;

//        $viewData['title'] = "Edit question";

        $this->load->view(get_folder($this->loggedUser->title).'/attitude_user_details_edit', $viewData);
    }

    function delete($id) {
//        $logged_in = $this->session->userdata('logged_in');
//        if ($logged_in['su'] != "1") {
//            exit('Permission denied');
//            return;
//        }
        $viewData['deleteResult'] = $this->attitudeuserdetail->delete($id);

        redirect('ss_kas/attitude_user_details', 'refresh');
    }

    function import() {
        $logged_in = $this->session->userdata('logged_in');
        if ($logged_in['su'] != "1") {
            exit('Permission denied');
            return;
        }
        if (isset($_FILES['xlsfile'])) {
            $targets = 'xls/';
            $targets = $targets . basename($_FILES['xlsfile']['name']);
            $docadd = ($_FILES['xlsfile']['name']);
            if (move_uploaded_file($_FILES['xlsfile']['tmp_name'], $targets)) {
                $Filepath = $targets;
                $allxlsdata = array();
                date_default_timezone_set('UTC');

                $StartMem = memory_get_usage();
                //echo '---------------------------------'.PHP_EOL;
                //echo 'Starting memory: '.$StartMem.PHP_EOL;
                //echo '---------------------------------'.PHP_EOL;

                try {
                    $Spreadsheet = new SpreadsheetReader($Filepath);
                    $BaseMem = memory_get_usage();

                    $Sheets = $Spreadsheet->Sheets();

                    //echo '---------------------------------'.PHP_EOL;
                    //echo 'Spreadsheets:'.PHP_EOL;
                    //print_r($Sheets);
                    //echo '---------------------------------'.PHP_EOL;
                    //echo '---------------------------------'.PHP_EOL;

                    foreach ($Sheets as $Index => $Name) {
                        //echo '---------------------------------'.PHP_EOL;
                        //echo '*** Sheet '.$Name.' ***'.PHP_EOL;
                        //echo '---------------------------------'.PHP_EOL;

                        $Time = microtime(true);

                        $Spreadsheet->ChangeSheet($Index);

                        foreach ($Spreadsheet as $Key => $Row) {
                            //echo $Key.': ';
                            if ($Row) {
                                //print_r($Row);
                                $allxlsdata[] = $Row;
                            } else {
                                var_dump($Row);
                            }
                            $CurrentMem = memory_get_usage();

                            //echo 'Memory: '.($CurrentMem - $BaseMem).' current, '.$CurrentMem.' base'.PHP_EOL;
                            //echo '---------------------------------'.PHP_EOL;

                            if ($Key && ($Key % 500 == 0)) {
                                //echo '---------------------------------'.PHP_EOL;
                                //echo 'Time: '.(microtime(true) - $Time);
                                //echo '---------------------------------'.PHP_EOL;
                            }
                        }

                        //	echo PHP_EOL.'---------------------------------'.PHP_EOL;
                        //echo 'Time: '.(microtime(true) - $Time);
                        //echo PHP_EOL;
                        //echo '---------------------------------'.PHP_EOL;
                        //echo '*** End of sheet '.$Name.' ***'.PHP_EOL;
                        //echo '---------------------------------'.PHP_EOL;
                    }
                } catch (Exception $E) {
                    echo $E->getMessage();
                }


                $this->qbank_model->import_question($allxlsdata);
            }
        } else {
            echo "Error: " . $_FILES["file"]["error"];
        }
        redirect('qbank');
    }

// get desired question for particular subject and difficulty level
    function get_level_question($difficulty_level, $category) {
        $this->db->where("cid", $category);
        $this->db->where("did", $difficulty_level);
        $query = $this->db->get("qbank");
        $num = $query->num_rows();
        echo $num;
    }

}
?>













